import java.io.File;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.highgui.Highgui;
import org.opencv.ml.CvSVM;
import org.opencv.ml.CvSVMParams;


public class TrainSVM {

	public static void trainSVM(){
		Mat classes = new Mat();
        Mat trainingData = new Mat();
        
        Mat trainingImages = new Mat();
        Mat trainingLabels = new Mat();

        String path = "C:\\Workspace\\reco\\hbot\\svm_train_data\\card";
        for (File file : new File(path).listFiles()) {
        	Mat con = Highgui.imread(file.getAbsolutePath(),Highgui.CV_LOAD_IMAGE_GRAYSCALE);
            trainingImages.push_back(con.reshape(1, 1));
            trainingLabels.push_back(Mat.ones(new Size(1, 1), CvType.CV_32FC1));
        }
        
        path="C:\\Workspace\\reco\\hbot\\svm_train_data\\no_card";
        for (File file : new File(path).listFiles()) {
              Mat con = Highgui.imread(file.getAbsolutePath(),Highgui.CV_LOAD_IMAGE_GRAYSCALE);
              trainingImages.push_back(con.reshape(1, 1));
              trainingLabels.push_back(Mat.zeros(new Size(1, 1), CvType.CV_32FC1));
            }

        trainingImages.copyTo(trainingData);
        trainingData.convertTo(trainingData, CvType.CV_32FC1);
        trainingLabels.copyTo(classes);

        CvSVMParams params = new CvSVMParams();
        params.set_kernel_type(CvSVM.LINEAR);
        CvSVM classificator = new CvSVM(trainingData, classes, new Mat(), new Mat(), params);
        
        classificator.save("C:\\Workspace\\reco\\hbot\\svm_train_data\\svm.xml");
        Mat out=new Mat();
        classificator.load("C:\\Workspace\\reco\\hbot\\svm_train_data\\svm.xml");
        
        Mat sample=Highgui.imread("C:\\Workspace\\reco\\hbot\\svm_train_data\\predict_1.png",Highgui.CV_LOAD_IMAGE_GRAYSCALE);
        sample.convertTo(out, CvType.CV_32FC1);               
        System.out.println("Predict 1 = " + classificator.predict(out.reshape(1, 1)));
        
        sample=Highgui.imread("C:\\Workspace\\reco\\hbot\\svm_train_data\\predict_0.png",Highgui.CV_LOAD_IMAGE_GRAYSCALE);
        sample.convertTo(out, CvType.CV_32FC1);
        System.out.println("Predict 0 = " + classificator.predict(out.reshape(1, 1)));
	}
}
